package com.example.blogsystem.impl;

import com.example.blogsystem.constant.Constants;
import com.example.blogsystem.mapper.BlogMapper;
import com.example.blogsystem.model.Blog;
import com.example.blogsystem.service.BlogService;
import com.example.blogsystem.utils.BlogStoreUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogMapper blogMapper;

    public List<Blog> queryAllBlogs(){
        return blogMapper.queryAllBlogs();
    }

    public Blog queryBlogById(Integer blogId){
        //从数据库中查询文章
        Blog blog = blogMapper.queryBlogById(blogId);
        //从文件中获取文章内容
        if(blog.getFileFlag() == 1){
            try {
                BlogStoreUtils.readBlog(blog);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return blog;
    }

    //如果博客内容的字数超过1k，则将博客储存在本地
    public void insertBlog(Blog blog){
        //1.检验文件内容
        if(blog.getContent().length() > Constants.BLOG_MAX_CONTENT){
            try {
                String content = BlogStoreUtils.writeBlog(blog);
                blog.setContent(content);
                blog.setFileFlag(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        blogMapper.insertBlog(blog);
    }

    public void updateBlog(Blog newBlog){
        Blog oldBlog = queryBlogById(newBlog.getId());
        oldBlog.setTitle(newBlog.getTitle());
        oldBlog.setContent(newBlog.getContent());
        blogMapper.updateBlog(oldBlog);
    }

    public void deleteBlog(Integer blogId){
        blogMapper.deleteBlogById(blogId);
    }

    public Integer countArticles(Integer id){
        return blogMapper.countArticles(id);
    }
}
